const path = require('path')
const viewsDir = path.join(__dirname, 'src/components/views/')
const chokidar = require('chokidar')
const updateRoutes = require('./watchComponents')

function debounce (fn, delay) {
    let timerId
    return function (...args) {
        clearTimeout(timerId)
        timerId = setTimeout(() => {
            fn.apply(this, args)
        }, delay)
    }
}

class BeforeHMR {
    constructor () {
        global.latestRoutes = updateRoutes('init')
        this.watcher = chokidar.watch(viewsDir, { ignoreInitial: true }).on('all', debounce((event, filename) => {
            updateRoutes()
        }, 300))
    }
    
    apply (compiler) {
        compiler.hooks.watchClose.tap('BeforeHMR', () => {
            this.watcher && this.watcher.close()
            this.watcher = null
        })
    }
}
  
module.exports = BeforeHMR
  
